﻿@using FFF.Test.Entity.FW.View;
@using Microsoft.AspNetCore.Http;
@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Index_Layout.cshtml";
    ViewFWUser currentUserInfo = base.Context.Session.GetUserInfo();
}

@if (!currentUserInfo.IsHaveRights("CF_BizOption", "00"))
{
    throw new Exception("您没有该页面的权限");
}

@section styles{
    <link href="~/lib/layui/layuiadmin/style/admin.css" rel="stylesheet" />
    <style type="text/css">
        [v-cloak] {
            display: none
        }
    </style>
}
@section scripts{
    <script src="~/lib/vue/vue.min.js"></script>

}

<div class="layui-fluid" id="DivApp" v-cloak style="min-height:600px">
    <div class="layui-card">
        <div class="layui-card-header">
            <div class="layui-btn-group">
                <button class="layui-btn" v-on:click="addGroup">增加组</button>
                <button class="layui-btn" v-on:click="importOption">引入</button>
                @*<button class="layui-btn" v-on:click="addOption">新增参数</button>*@
            </div>
        </div>
        <div class="layui-card-body" style="padding: 15px;">
            <form class="layui-form" action="" lay-filter="component-form-element">
                <div class="layui-card" v-for="groupItem in pageData">
                    <div class="layui-card-header">
                        <blockquote class="layui-elem-quote" style="line-height:10px">
                            <span v-on:click="editGroup(groupItem.bizConfigGroupGUID)" style="cursor:pointer">{{groupItem.bizConfigGroupName}}</span>
                            <button class="layui-btn layui-btn-xs" type="button" v-on:click="addOption(groupItem.bizConfigGroupGUID)" style="position:absolute;right:70px;bottom:10px">新增参数</button>
                            <button class="layui-btn layui-btn-xs" type="button" v-on:click="deleteGroup(groupItem.bizConfigGroupGUID)" style="position:absolute;right:20px;bottom:10px">删除</button>
                        </blockquote>
                    </div>
                    <div class="layui-card-body">
                        <div class="layui-row layui-form-item" v-for="valueItem in groupItem.items">
                            <div class="layui-col-md11">
                                <label class="layui-form-label" v-on:click="editOption(valueItem.id)" style="cursor:pointer">{{valueItem.bizConfigOptionName}}：</label>
                                <div class="layui-input-block">
                                    <input type="text" :name="valueItem.bizOptionCode+'_'+valueItem.id" :value="valueItem.bizOptionValue" placeholder="" autocomplete="off" class="layui-input" v-if="valueItem.bizOptionType==1">
                                    <input type="text" :name="valueItem.bizOptionCode+'_'+valueItem.id" :value="valueItem.bizOptionValue" placeholder="" autocomplete="off" class="layui-input" v-else-if="valueItem.bizOptionType==2">
                                    <input type="radio" :name="valueItem.bizOptionCode+'_'+valueItem.id" :value="optiobItem.value" :title="optiobItem.name" v-else-if="valueItem.bizOptionType==3" v-for="optiobItem in valueItem.options" v-model="valueItem.bizOptionValue">

                                    <input type="checkbox" lay-skin="primary" :value="optiobItem.value" :name="valueItem.bizOptionCode+','+index+'_'+valueItem.id" :title="optiobItem.name" v-else-if="valueItem.bizOptionType==4" v-for="(optiobItem,index) in valueItem.options" v-model="valueItem.values">

                                    <input type="text" :name="valueItem.bizOptionCode+'_'+valueItem.id" :value="valueItem.bizOptionValue" placeholder="" autocomplete="off" class="layui-input LayUI-Date" v-else-if="valueItem.bizOptionType==5">
                                    <select :name="valueItem.bizOptionCode+'_'+valueItem.id" lay-verify="required" v-else-if="valueItem.bizOptionType==6" :value="valueItem.bizOptionValue">
                                        <option value=""></option>
                                        <option :value="optiobItem.value" v-for="optiobItem in valueItem.options">{{optiobItem.name}}</option>
                                    </select>
                                </div>
                            </div>
                            <div class="layui-col-md1" style="top:5px">
                                <button class="layui-btn layui-btn-xs" type="button" v-on:click="deleteOption(valueItem.id,groupItem.bizConfigGroupGUID)">删除参数</button>
                            </div>

                        </div>
                    </div>
                </div>
                <div class="layui-form-item layui-layout-admin">
                    <div class="layui-input-block">
                        <div class="layui-footer" style="left: 0;height:30px">
                            <button class="layui-btn" lay-submit="" lay-filter="component-form-demo1">保存</button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    var queryObj = $.dm.getQueryObj();
    $(function () {
        var vmDivApp = new Vue({
            el: '#DivApp',
            data: {
                pageData: [],
                pageQuery: {
                    pageIndex: 1,
                    pageSize: 9999,
                    order: 'createTime desc',
                    filter: {
                        Type: 'and',
                        Conditions: [
                            {
                                Attribute: 'bizOptionScopeGUID',
                                Datatype: 'uniqueidentifier',
                                Operatoer: 'eq',
                                Value: queryObj.bizParamScopeGUID
                            }
                        ]
                    }
                }
            },
            methods: {
                getPageData: function () {
                    var self = this;
                    var data = {
                        bizOptionScopeGUID:null
                    };
                    if (queryObj.bizParamType != '1') {
                        data.bizOptionScopeGUID = queryObj.bizParamScopeGUID;
                    }
                    var options = {
                        url: '/api/services/app/CFBizConfigGroup/GetConfigInfo',
                        data: data
                    };
                    var success = function (result) {
                        self.pageData = result.dtos;
                        self.$nextTick(function () {
                            initLayIM();
                            // DOM 现在更新了
                            // `this` 绑定到当前实例
                        });
                    }
                    abp.ajax(options).done(success);
                },
                addGroup: function () {
                    oepnAddDiag(this);
                },
                editGroup: function (id) {
                    openEditDiag(id, this);
                },
                deleteGroup: function (id) {
                    var self = this;
                    $.messager.confirm("@L("确认")", "@L("您确认想要删除这组吗？")", function (r) {
                        if (r) {
                            var data = { id: id }
                            var options = {
                                url: '/api/services/app/CFBizConfigGroup/DeleteByDto',
                                maskJqSelect: '#DivApp',
                                data: data
                            };
                            var success = function (result) {
                                _.remove(self.pageData, function (x) {
                                    return x.bizConfigGroupGUID == id;
                                });
                                self.pageData.splice(self.pageData.length);
                            }
                            abp.ajax(options).done(success);
                        }
                    });
                },
                addOption: function (groupId) {
                    oepnOptionAddDiag(this,groupId);
                },
                editOption: function (id) {
                    openOptionEditDiag(id);
                },
                deleteOption: function (id, groupId) {
                    deleteRow(id,groupId,this);
                },
                importOption: function () {
                    importDialog(this);
                }
            },
            mounted: function () {
                this.getPageData();
            },
            computed: {
                //fullName: {
                //    get: function () {
                //        return this.firstName + ' ' + this.lastName
                //    },
                //    set: function (newValue) {
                //        var names = newValue.split(' ')
                //        this.firstName = names[0]
                //        this.lastName = names[names.length - 1]
                //    }
                //}
                // vm.fullName = 'John Doe'
            },
            filters: {
                //parseScene: function (value) {
                //}
            },
            watch: {
                //"currentStore.storeId": {
                //    handler: function (val, oldval) {
                //        if (val) {
                //            vmDivItem1.$options.methods.getMonthSummaryData.bind(vmDivItem1)(1, val);
                //            vmDivItem3.$options.methods.getTodyBookData.bind(vmDivItem3)(1, val);
                //        }
                //    }
                //}
            }
        });
    })

    function openEditDiag(uuid,self) {
        if (!uuid) {
            var selectedRow = $('#myDg').iDatagrid('getSelected');
            uuid = selectedRow.id;
        }
        var $editDialog = $('<form id="myFormDialog"></form>'); // 创建form表单元素
        $editDialog.iDialog({
            title: '@L("编辑配置类业务参数表")',
            width: 750,
            height: 550,
            closed: false,
            cache: false,
            maximized: false, // 初始化是否最大化
            href: '/CF/CFBizConfigGroup/CFBizConfigGroupEdit?uuid=' + uuid+'&mode=2',
            // modal: true,
            buttons: [
            {
                text: '@L("保存")',
                iconCls: 'fa fa-save',
                btnCls: 'topjui-btn-blue',
                handler: function () {
                    // 1. 显示进度条（提交时请使用进度条 或者 禁用'提交'按钮，防止因为网络延迟用户重复提交）
                    $.iMessager.progress({ 'text': '@L("保存中...")' });
                    var isValid = $('#myFormDialog').iForm('validate'); //  提交数据表单数据时进行表单验证
                    if (!isValid) {
                        layer.msg('@L("格式不正确,请填写对应的必填项!")');
                        $.iMessager.progress('close');  // 如果表单是无效的则隐藏进度条
                        return;
                    }

                    var data = $.dm.parseQueryString($('#myFormDialog').serialize());
                    var options = {
                        url: '/api/services/app/CFBizConfigGroup/UpdateByDto',
                        data: data
                    };


                    var success = function (result) {
                        var data = self.pageData;
                        var index = _.findIndex(data, function (item) {
                            return item.bizConfigGroupGUID == result.id;
                        });
                        self.pageData[index].bizConfigGroupName = result.bizConfigGroupName;

                        data.splice(self.pageData.length);
                        $('#myFormDialog').iDialog('close');// 销毁dialog面板
                        layer.msg("@L("保存成功")");
                    }
                    abp.ajax(options).done(success);
                }
            },
            {
                text: '@L("关闭")',
                iconCls: 'fa fa-close',
                btnCls: 'topjui-btn-red',
                handler: function () {
                    $('#myFormDialog').iDialog('close');// 销毁dialog面
                }
            }],
            onLoad: function () {
                var data = { 'id': uuid };
                var options = {
                    url: '/api/services/app/CFBizConfigGroup/GetViewDto',
                    maskJqSelect: '#myFormDialog',
                    data:data
                };

                var success = function (result) {
                    $editDialog.iForm('load', result);
                }

                abp.ajax(options).done(success);
            }
        });
    }

    function importDialog(self) {
        var $editDialog = $('<form id="myFormDialog"></form>'); // 创建form表单元素
        $editDialog.iDialog({
            title: '@L("引入参数")',
            width: 750,
            height: 300,
            href: '/Common/Select/SelectBuUnit?mode=1',
            closed: false,
            cache: false,
            maximized: false, // 初始化是否最大化
            buttons:[{
                text: '@L("保存")',
                iconCls: 'fa fa-save',
                btnCls: 'topjui-btn-blue',
                handler: function () {
                    // 1. 显示进度条（提交时请使用进度条 或者 禁用'提交'按钮，防止因为网络延迟用户重复提交）
                    $.iMessager.progress({ 'text': '@L("保存中...")' });
                    var isValid = $(this).iForm('validate'); //  提交数据表单数据时进行表单验证
                    if (!isValid) {
                        layer.msg('@L("格式不正确,请填写对应的必填项!")');
                        $.iMessager.progress('close');  // 如果表单是无效的则隐藏进度条
                        return;
                    }
                    var data = $.dm.parseQueryString($('#myFormDialog').serialize());
                    if (queryObj.bizParamType != "1") {
                        data.targetScopeGUID = queryObj.bizParamScopeGUID;
                    }
                    var options = {
                        url: '/api/services/app/CFBizConfigOption/ImportConfigOption',
                        data: data
                    };

                    var success = function (result) {
                        $('#myFormDialog').iDialog('close'); // 销毁dialog面板
                        layer.msg("@L("保存成功")");
                        window.location.reload();
                    }
                    abp.ajax(options).done(success);
                }
            },
            {
                text: '@L("关闭")',
                iconCls: 'fa fa-close',
                btnCls: 'topjui-btn-red',
                handler: function () {
                    $("#myFormDialog").iDialog('close');// 销毁dialog面
                }
            }],
            onLoad: function () {
            }
        });
    }

   // 删除行数据
    function deleteRow(id, groupId, self) {
        $.messager.confirm("@L("提示")", "@L("确定要删除该条数据吗?")", function (result) {
            if (result) {
                $.iMessager.progress({ 'text': '@L("处理中...")' });
                var data={'id':id};
                var options = {
                    url: '/api/services/app/CFBizConfigOption/DeleteByDto',
                    maskJqSelect: '#myDg',
                    data: data
                };

                var success = function (result) {
                    var data = self.pageData;
                    var index = _.findIndex(data, function (item) {
                        return item.bizConfigGroupGUID == groupId;
                    });

                    _.remove(data[index].items, function (bizOption) {
                        return bizOption.id == id;
                    });

                    data.splice(self.pageData.length);

                    // Vue.set(self.pageData, data[index], data[index]);
                    self.$nextTick(function () {
                        initLayFrom();
                    })
                }

                abp.ajax(options).done(success);
            }
        })
    }

    var from = null;
    function initLayIM() {
        layui.config({
            base: '/lib/layui/layuiadmin/' //静态资源所在路径
        }).extend({
            index: 'lib/index' //主入口模块
        }).use(['index', 'form', 'laydate'], function () {
            var $ = layui.$
                , admin = layui.admin
                , element = layui.element
                , laydate = layui.laydate
                , form = layui.form;
                laydate.render({
                    elem: '.LayUI-Date'
                });
            from = form;

            form.on('submit(component-form-demo1)', function (data) {
                var obj = data.field;
                var keys = Object.keys(obj);
                var data =
                {
                    ids: [],
                    values: [],
                    bizOptionScopeGUID:'00000000-0000-0000-0000-000000000000'
                };
                if (queryObj.bizParamType != "1") {
                    data.bizOptionScopeGUID = queryObj.bizParamScopeGUID
                }

                _.forEach(keys, function (item) {
                    var id = item.split("_")[1];
                    data.ids.push(id);
                    data.values.push(obj[item]);
                });


                var options = {
                    url: '/api/services/app/CFBizConfigOption/BatchSaveOptions',
                    maskJqSelect: '#DivApp',
                    data: data
                };

                var success = function (result) {
                      layer.msg("@L("保存成功")");
                }
                abp.ajax(options).done(success);
                return false;
            });
        });
    }

    function initLayFrom() {
        from.render();
    }



    function oepnAddDiag(self) {
        var $editDialog = $('<form id="myFormDialog"></form>'); // 创建form表单元素
        $editDialog.iDialog({
            title: '@L("新增配置类业务参数分组表")',
            width: 750,
            height: 300,
            closed: false,
            cache: false,
            maximized: false, // 初始化是否最大化
            href: '/CF/CFBizConfigGroup/CFBizConfigGroupEdit?mode=1',
                buttons: [{
                text: '@L("保存")',
                iconCls: 'fa fa-save',
                btnCls: 'topjui-btn-blue',
                handler: function () {
                    // 1. 显示进度条（提交时请使用进度条 或者 禁用'提交'按钮，防止因为网络延迟用户重复提交）
                    $.iMessager.progress({ 'text': '@L("保存中...")' });
                    var isValid = $('#myFormDialog').iForm('validate'); //  提交数据表单数据时进行表单验证
                    if (!isValid) {
                        layer.msg('@L("格式不正确,请填写对应的必填项!")');
                        $.iMessager.progress('close');  // 如果表单是无效的则隐藏进度条
                        return;
                    }

                    var data = $.dm.parseQueryString($('#myFormDialog').serialize());
                    if (queryObj.bizParamType != "1") {
                        data.bizGroupScopeGUID = queryObj.bizParamScopeGUID;
                    }
                    var options = {
                        url: '/api/services/app/CFBizConfigGroup/CreateByDto',
                        data: data
                    };


                    var success = function (result) {
                        var group = {
                            bizConfigGroupName: result.bizConfigGroupName,
                            bizConfigGroupGUID: result.id,
                            items: []
                        };
                        self.pageData.unshift(group);
                        $('#myFormDialog').iDialog('close');// 销毁dialog面板
                        layer.msg("@L("保存成功")");
                    }
                    abp.ajax(options).done(success);
                }
            },
            {
                text: '@L("关闭")',
                iconCls: 'fa fa-close',
                btnCls: 'topjui-btn-red',
                handler: function () {
                    $('#myFormDialog').iDialog('close');// 销毁dialog面
                }
            }],
            onLoad: function () {
            }
        });
    }


    function oepnOptionAddDiag(self, groupId) {
        var $editDialog = $('<form id="myFormDialog"></form>'); // 创建form表单元素
        $editDialog.iDialog({
            title: '@L("新增配置类业务参数表")',
            width: 750,
            height: 550,
            closed: false,
            cache: false,
            maximized: false, // 初始化是否最大化
            href: '/CF/CFBizConfigOption/CFBizConfigOptionEdit?mode=1&' + $.param(queryObj),
                buttons: [{
                text: '@L("保存")',
                iconCls: 'fa fa-save',
                btnCls: 'topjui-btn-blue',
                handler: function () {
                    saveOptionDate("saveAndClose");
                }
            },
            {
                text: '@L("关闭")',
                iconCls: 'fa fa-close',
                btnCls: 'topjui-btn-red',
                handler: function () {
                    $('#myFormDialog').iDialog('close');// 销毁dialog面
                }
            }],
            onLoad: function () {
                var result = {
                    bizConfigGroupGUID: groupId
                };
                $editDialog.iForm('load', result);
            }
        });
    }

    function openOptionEditDiag(uuid) {
        if (!uuid) {
            var selectedRow = $('#myDg').iDatagrid('getSelected');
            uuid = selectedRow.id;
        }
        var $editDialog = $('<form id="myFormDialog"></form>'); // 创建form表单元素
        $editDialog.iDialog({
            title: '@L("编辑配置类业务参数表")',
            width: 750,
            height: 550,
            closed: false,
            cache: false,
            maximized: false, // 初始化是否最大化
            href: '/CF/CFBizConfigOption/CFBizConfigOptionEdit?uuid=' + uuid + '&mode=2' + "&" + $.param(queryObj),
            buttons: [
            {
                text: '@L("保存")',
                iconCls: 'fa fa-save',
                btnCls: 'topjui-btn-blue',
                handler: function () {
                    saveOptionDate("saveAndClose");
                }
            },
            {
                text: '@L("关闭")',
                iconCls: 'fa fa-close',
                btnCls: 'topjui-btn-red',
                handler: function () {
                    $('#myFormDialog').iDialog('close'); // 销毁dialog面
                }
            }],
            onLoad: function () {
                var data = { 'id': uuid };
                var options = {
                    url: '/api/services/app/CFBizConfigOption/GetViewDto',
                    maskJqSelect: '#myFormDialog',
                    data:data
                };

                var success = function (result) {
                    $editDialog.iForm('load', result);

                    // 绑定combox
                    $editDialog.find('[data-toggle="topjui-combobox"]').each(function (b) {
                        var c = $(this);
                        var opt = getOptionsJson(c);
                        if (opt.queryParams.viewName) {
                            c.iCombobox(opt);
                        }
                    });

                    // 在这里进行绑定UeEditor
                    $editDialog.find('[data-toggle="topjui-ueditor"]').each(function (b) {
                        var c = $(this);
                        var name = c.attr('name');
                        var opt = getOptionsJson(c);
                        var id = opt.id;
                        var ue = UE.getEditor(id);
                        ue.ready(function () {
                            ue.setContent(result[name]);
                        });
                    });
                }

                abp.ajax(options).done(success);
            }
        });
    }

    // operate表示操作类型有 save saveAndClose saveAndNew
    function saveOptionDate(operate) {
        // 1. 显示进度条（提交时请使用进度条 或者 禁用'提交'按钮，防止因为网络延迟用户重复提交）
        $.iMessager.progress({ 'text': '@L("保存中...")' });
        var isValid = $('#myFormDialog').iForm('validate'); //  提交数据表单数据时进行表单验证
        if (!isValid) {
            layer.msg('@L("格式不正确,请填写对应的必填项!")');
            $.iMessager.progress('close');  // 如果表单是无效的则隐藏进度条
            return;
        }

        var data = $.dm.parseQueryString($('#myFormDialog').serialize());
        if (queryObj.bizParamType != "1") {
            data.bizOptionScopeGUID = queryObj.bizParamScopeGUID;
        }
        var options = {
            url: '/api/services/app/CFBizConfigOption/CreateByDto',
            data: data
        };

        // 有ID就是更新
        if (data.id) {
            options.url = '/api/services/app/CFBizConfigOption/UpdateByDto'
        }
        var success = function (result) {
            $('#myFormDialog').iForm('load', { id: result.id });
            // 保存并关闭
            if (operate === 'saveAndClose') {
                layer.msg("@L("保存成功")");
                $('#myFormDialog').iDialog('close');// 销毁dialog面板
                window.location.reload();
            } else if (operate === 'saveAndNew') {
                // 保存新增重置form
                $("#uuid").val(""); // 清空GUID
                $('#myFormDialog').iForm('reset');
                // UE.getEditor('myFormDayReportDesc').setContent('');
                formAddInit($('#myFormDialog'));
                layer.msg("@L("保存成功")");
            } else {
                layer.msg("@L("保存成功")");
            }
        }
        abp.ajax(options).done(success);
    }

</script>



